package faf.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import faf.business.UserManager;
import faf.entities.Account;
import faf.web.data.AuthentificationForm;

public class AuthentificationController extends SimpleFormController {

	UserManager userManager;

	public void setUserManager(UserManager userManager) {
		this.userManager = userManager;
	}
	
	public ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		AuthentificationForm form = (AuthentificationForm) command;
		
		Account account = userManager.login(form.getEmail(), form.getPassword());
		
		if (account == null) { // login failed
			errors.rejectValue("email", "email-login-failed");
			return showForm(request, response, errors);
		} else {
			request.getSession().setAttribute("user", account);
			
			String nextUrl = (String) request.getParameter("nexturl");
			if (nextUrl != null)
				return new ModelAndView(new RedirectView(nextUrl));
			
			return new ModelAndView(new RedirectView(getSuccessView()));
		}
	}
}
